﻿/*
 * Erstellt mit SharpDevelop.
 * Benutzer: Kai Patrick
 * Datum: 04.04.2008
 * Zeit: 18:15
 * 
 * Sie können diese Vorlage unter Extras > Optionen > Codeerstellung > Standardheader ändern.
 */
using System;
using System.Reflection;
using System.IO;

partial class Game
{
	static string tempDir;
	
	public static void Main(string[] args)
	{
		do
		{
			tempDir = Path.GetTempPath()+Path.GetRandomFileName();
		}
		while(Directory.Exists(tempDir));
		tempDir += Path.DirectorySeparatorChar;
		
		AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
		
		//TODO: register AppDomain.CurrentDomain.DomainUnload or ProcessExit to delete temp files
		
		Console.WriteLine("Loading Engine...");
		
		LoadSettings();
		
		Gamadus.Engine.Engine.Instance.Init();
		
		Gamadus.Engine.RoomMgr.Instance.PopulateRoom += Populate;
		//calls the main setup created by the builder
		Setup();

    	Gamadus.Engine.Engine.Instance.Run();
	}
	private static Assembly OnAssemblyResolve(object sender,ResolveEventArgs e)
	{
		if(!Directory.Exists(tempDir))
			Directory.CreateDirectory(tempDir);
		
		string assemblyFile = e.Name.Substring(0,e.Name.IndexOf(","))+".dll";

    	Console.WriteLine("Unpacking "+assemblyFile+" to "+tempDir+assemblyFile);
    	System.Resources.ResourceManager rm = new System.Resources.ResourceManager("runtime", System.Reflection.Assembly.GetExecutingAssembly());
    	object obj = rm.GetObject(assemblyFile);
    	if(obj == null)
    		throw new FileNotFoundException("Runtime assembly "+assemblyFile+" couldn't be found");
    	BinaryWriter bw;
		byte[] bytes = (byte[])obj;
		bw = new BinaryWriter(new StreamWriter(tempDir+assemblyFile, false).BaseStream);
		bw.Write(bytes);
		bw.Close();
		//load config file if there is one
		obj = rm.GetObject(assemblyFile+".config");
		if(obj != null)
		{
			Console.WriteLine("Unpacking "+assemblyFile+".config to "+tempDir+assemblyFile+".config");
			bytes = (byte[])obj;
			bw = new BinaryWriter(new StreamWriter(tempDir+assemblyFile+".config", false).BaseStream);
			bw.Write(bytes);
			bw.Close();
		}
		return Assembly.LoadFrom(tempDir+assemblyFile);
	}
}